/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, BlobInputList, Table, TableBody, TableRow, CCell, TableHead, Cell, Input,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink, useItemInputControl,} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {Each_ZdSetting, tabIBlistCb, useRaftTableViewer, useTableEditor} from "../../hook/useRepTableEditor";

const 时间选=['8:00','20:00'];
type ForkLoopTime = {
    g?: number;
    t?: number;
    F?: number;
    W?: number;
    O?: number;
};
//统计字段  的累计汇总数字
const sumFields = (arr: ForkLoopTime[]) => {
    return arr.reduce((acc, obj) => {
        acc.g! += Number(obj.g) ||0;
        acc.t! += Number(obj.t) ||0;
        acc.F! += Number(obj.F) ||0;
        acc.W! += Number(obj.W) ||0;
        acc.O! += Number(obj.O) ||0;
        return acc;
    }, {g: 0, t: 0,F:0, W:0, O:0});
};
//双层的表头：
const config试验台班=[['月','m',35],['日','d',35],['上午','b',45,tabIBlistCb(时间选,1)],['下午','e',60,tabIBlistCb(时间选,1)],
        ['循环频率','f',65,],['循环数','g',60,],['作业时间','t',65,],['故障停机','F',65,],['保养时间','W',65,],['其它停机','O',65,],
        ['停机内容','M',170,tabIBlistCb(['保养、补充充电、休息'],2)]
] as Each_ZdSetting[];
export const itemA试台班=['台班表','台班备注' ];
export const TestbedShift=
    React.forwardRef(({ children, show ,alone=true,refWidth,label,}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA试台班,);
        const {inp, setInp} = useItemInputControl({ ref });
        const headview=<Text variant="h6">
           以下简写和省略单位。
        </Text>;
        const [render]=useTableEditor({inp,setInp,
                         headview, config: config试验台班, table:'台班表', });
        const sumobj= React.useMemo(()=> {
            return inp?.台班表? sumFields(inp?.台班表) : {};
        }, [inp?.台班表]);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}
                                 alone={alone}  label={label!}>
                <Text variant="h5">{label}：</Text>
                样表格式如下：
                <Table tight  miniw={800}><TableBody>
                    <TableRow>
                        <CCell colSpan={2}>试验日期</CCell><CCell colSpan={2}>作业始末时间</CCell><CCell rowSpan={2}>平均循环频率（个/h）</CCell>
                        <CCell rowSpan={2}>作业循环数（个）</CCell><CCell rowSpan={2}>作业时间（h）</CCell><CCell colSpan={4}>停机说明</CCell>
                    </TableRow>
                    <TableRow>
                        <CCell>月</CCell><CCell>日</CCell><CCell>上午</CCell><CCell>下午</CCell>
                        <CCell>故障停机时间（h）</CCell><CCell>维护保养时间（h）</CCell><CCell>其它停机时间（h）</CCell><CCell>停机内容（含故障内容）</CCell>
                    </TableRow>
                </TableBody></Table>
                {render}
                <hr/>
                累计: 作业循环数 {sumobj.g}（个）; 作业时间 {sumobj.t}（h）; 故障停机时间 {sumobj.F}（h）;维护保养时间 {sumobj.W}（h）;其它停机时间 {sumobj.O}（h）;<br/>
                备注：
                <BlobInputList value={inp?.台班备注 || ''} rows={4}
                               onListChange={v => setInp({ ...inp, 台班备注 :v || undefined}) } />
                { children }
            </InspectRecordLayout>
        );
} );
//附表12-1 试验台班
export const TestbedShiftVw= ({orc, rep,label} :{orc:any, rep:any,label?:string}
) => {
    const [renderRows]=useRaftTableViewer(config试验台班, orc?.台班表,1,
                true, true, true);
    const sumobj= React.useMemo(()=> {
        return orc?.台班表? sumFields(orc?.台班表) : {};
    }, [orc?.台班表]);
    return <>
        <div css={{"@media print": {paddingBottom: '6rem', pageBreakInside: 'avoid'}} }>
            <Text id='TestbedShift' variant="h4" css={{textAlign: 'center', marginTop: '1rem',
            }}>{label}</Text>
        </div>
        <Table fixed={ ["4%","4.1%","5.1%","7.1%","8%","10%","7%","10%","10%","10%","%"] }
                     css={{borderCollapse: 'collapse',"@media print": {marginTop: '-6rem'} }} tight  miniw={800}>
            <TableHead>
                <TableRow>
                    <CCell colSpan={2}>试验日期</CCell><CCell colSpan={2}>作业始末时间</CCell><CCell rowSpan={2}>平均循环频率(个/h)</CCell>
                    <CCell rowSpan={2}>作业循环数（个）</CCell><CCell rowSpan={2}>作业时间(h)</CCell><CCell colSpan={4}>停机说明</CCell>
                </TableRow>
                <TableRow>
                    <CCell>月</CCell><CCell>日</CCell><CCell>上午</CCell><CCell>下午</CCell>
                    <CCell>故障停机时间（h）</CCell><CCell>维护保养时间（h）</CCell><CCell>其它停机时间（h）</CCell><CCell>停机内容（含故障内容）</CCell>
                </TableRow>
            </TableHead>
            <TableBody>
                <RepLink ori rep={rep} tag={'TestbedShift'}>
                    {renderRows}
                    <TableRow>
                        <CCell colSpan={5}>累计</CCell><CCell>{sumobj.g}</CCell><CCell>{sumobj.t}</CCell>
                        <CCell>{sumobj.F}</CCell><CCell>{sumobj.W}</CCell><CCell>{sumobj.O}</CCell><CCell>／</CCell>
                    </TableRow>
                    <TableRow>
                        <Cell colSpan={11}><div css={{minHeight: '2rem',whiteSpace:'pre-wrap'
                        }}>备注：<br/>{orc.台班备注}</div></Cell>
                    </TableRow>
                </RepLink>
            </TableBody>
        </Table>
    </>;
};
/*其余类似页面
* */
const config强化障=[['故障发生时间','a',170,tabIBlistCb(['月日时分'],1)],
            ['累计试验时间','s',100],['故障排除时间','R',100], ['故障类别','c',90], ['系数','F',50,]] as Each_ZdSetting[];
export const itemA强化障=['强障表','强化障内' ];
export const FaultRecord=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,label,}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA强化障,);
        const {inp, setInp} = useItemInputControl({ ref });
        const headview=<Text variant="h6">
            以下故障发生时间,按月 日 时 分录入：
        </Text>;
        const [render]=useTableEditor({inp,setInp,
                               headview, config: config强化障, table:'强障表', });
        return <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show} redId={redId}
                                    nestMd={nestMd} alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {render}
            <hr/>
            故障内容：
            <BlobInputList value={inp?.强化障内 || ''} rows={8}
                           onListChange={v => setInp({...inp, 强化障内: v || undefined})}/>
            {children}
        </InspectRecordLayout>;
});
//附表12-2 强化试验故障
export const FaultRecordVw = ({orc, rep, label,}: { orc: any, rep: any, label: string }
) => {
    const [renderRows]=useRaftTableViewer(config强化障, orc?.强障表,1,
                  true, true, true,'序');
    return <>
        <div css={{"@media print": {paddingBottom: '5rem', pageBreakInside: 'avoid'}}}>
            <Text id='FaultRecord' variant="h4" css={{marginTop: '1rem',
            }}>{label}</Text>
        </div>
        <Table fixed={ ["5.1%", "%", "21%", "10%","32%","9%"] }
                      css={{borderCollapse: 'collapse', "@media print": {marginTop: '-5rem'}}} tight miniw={800}>
            <TableHead>
                <TableRow>
                    <CCell>序号</CCell><CCell>故障发生时间<br/>月 日 时 分</CCell>
                    <CCell>样机累计完成试验时间</CCell><CCell>故障排除时间</CCell><CCell>故障类别</CCell><CCell>故障系数</CCell>
                </TableRow>
            </TableHead>
            <TableBody>
                <RepLink ori rep={rep} tag={'FaultRecord'}>
                    {renderRows}
                    <TableRow>
                        <Cell colSpan={6}><div css={{whiteSpace:'pre-wrap'
                        }}>故障内容：<br/>{orc.强化障内}</div></Cell>
                    </TableRow>
                </RepLink>
            </TableBody>
        </Table>
    </>;
};

/*其余关联页面
* */
const sumFieldsRl = (arr: ForkLoopTime[]) => {
    return arr.reduce((acc, obj) => {
        acc.t! += Number(obj.t) ||0;
        acc.F! += Number(obj.F) ||0;
        acc.W! += Number(obj.W) ||0;
        return acc;
    }, {t: 0,F:0, W:0});
};
export const itemA可靠性: string[] = ['障统总','障统致命','障统重大','障统一般','障统MT','障统效' ];
export const Reliability =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, }: InternalItemProps, ref
    ) => {
        const itemA = React.useMemo(() => {
            return ['台班表', ...itemA可靠性 ];
        }, []);
        const {inp, setInp} = useItemInputControl({ref});
        const [getInpFilter] = useMeasureInpFilter(null, itemA,);
        const sumobj= React.useMemo(()=> {
            return inp?.台班表? sumFieldsRl(inp?.台班表) : {};
        }, [inp?.台班表]);
        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={label!}>
                <Text variant="h5">{label}：</Text>
                从附表 12-1 获得数据：强化试验时间= {sumobj.t} (h)；保养和排除故障时间总和= {sumobj.F!+sumobj.W! ||''} (h)；<br/>
                强化试验数据：
                <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'center'}}>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        当量故障总数:
                        <Input value={inp?.障统总 || ''} size={2} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统总: e.currentTarget.value || undefined})}/>
                        （次）；
                    </div>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        统计致命故障：
                        <Input value={inp?.障统致命 || ''} size={2} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统致命: e.currentTarget.value || undefined})}/>
                        （次）；
                    </div>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        统计重大故障：
                        <Input value={inp?.障统重大 || ''} size={2} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统重大: e.currentTarget.value || undefined})}/>
                        （次）；
                    </div>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        统计一般故障：
                        <Input value={inp?.障统一般 || ''} size={2} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统一般: e.currentTarget.value || undefined})}/>
                        （次）；
                    </div>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        平均无故障工作时间MTBF=
                        <Input value={inp?.障统MT || ''} size={5} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统MT: e.currentTarget.value || undefined})}/>
                        （h）；
                    </div>
                    <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        有效度=
                        <Input value={inp?.障统效 || ''} size={3} style={{display: 'inline-flex', width: 'unset'}}
                               onChange={e => setInp({...inp, 障统效: e.currentTarget.value || undefined})}/>
                        （%）；
                    </div>
                </div>
                {children}
    </InspectRecordLayout>);
});
//附表12-3 可靠性强化试验
export const ReliabilityVw = ({orc, rep, label}: { orc: any, rep: any, label?: string }
) => {
    const sumobj = React.useMemo(() => {
        return orc?.台班表 ? sumFieldsRl(orc?.台班表) : {};
    }, [orc?.台班表]);
    return <>
        <div css={{"@media print": {paddingBottom: '5.5rem', pageBreakInside: 'avoid'}}}>
            <Text variant="h4" css={{marginTop: '1rem'}}>{label}</Text>
        </div>
        <Table id='Reliability' fixed={["10%","20%","30%","%"]}
                css={{borderCollapse: 'collapse', "@media print": {marginTop: '-5.5rem'}}} tight miniw={800}>
            <TableHead>
                <TableRow><CCell colSpan={4}>强化试验数据</CCell></TableRow>
                <TableRow><CCell>序号</CCell><CCell colSpan={2}>试验项目及其内容</CCell><CCell>试验结果</CCell></TableRow>
            </TableHead>
            <TableBody>
                <RepLink ori rep={rep} tag={'Reliability'}>
                    <TableRow><CCell>1</CCell><CCell colSpan={2}>强化试验时间</CCell><CCell>{sumobj.t}</CCell></TableRow>
                    <TableRow><CCell>2</CCell><CCell colSpan={2}>保养和排除故障时间总和</CCell><CCell>{sumobj.F!+sumobj.W! ||''}</CCell></TableRow>
                    <TableRow><CCell>3</CCell><CCell colSpan={2}>当量故障总数</CCell><CCell>{orc?.障统总}</CCell></TableRow>
                    <TableRow>
                        <CCell rowSpan={3}>4</CCell><CCell rowSpan={3}>故障统计（次）</CCell>
                        <CCell>致命故障</CCell><CCell>{orc?.障统致命}</CCell>
                    </TableRow>
                    <TableRow><CCell>重大故障</CCell><CCell>{orc?.障统重大}</CCell></TableRow>
                    <TableRow><CCell>一般故障</CCell><CCell>{orc?.障统一般}</CCell></TableRow>
                    <TableRow><CCell>5</CCell><CCell colSpan={2}>平均无故障工作时间MTBF &nbsp;（h）</CCell><CCell>{orc?.障统MT}</CCell></TableRow>
                    <TableRow><CCell>6</CCell><CCell colSpan={2}>有效度 &nbsp;（%）</CCell><CCell>{orc?.障统效}</CCell></TableRow>
                </RepLink>
            </TableBody>
        </Table>
    </>;
};
